# encoding=utf-8
from common import HTMLTestRunner_for_py3
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import parseaddr, formataddr
import smtplib
import unittest
import time
import os
import smtplib
from email.mime.text import MIMEText


# def _format_addr(s):
#     name, addr = parseaddr(s)
#     return formataddr(( \
#         Header(name, 'utf-8').encode(), \
#         addr.encode('utf-8') if isinstance(addr, 'unicode') else addr))

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


## ==============定义发送附件邮件==========
def send_file(file_new):
    # smtpserver = 'smtp.qtshe.com'
    # user = 'chenchi@qtshe.com'
    # password = 'cnp200@HW'
    # sender = 'chenchi@qtshe.com'
    # receiver = ['chenchi@qtshe.com']
    # # subject='**自动化测试报告'
    # file = open(file_new, 'r').read()
    #
    # now = time.strftime("%Y-%m-%d %H_%M_%S")
    # subject = 'OpenAPI自动化测试报告--' + now
    # # att=MIMEText(sendfile,"base64","utf-8")
    # att = MIMEText(file, "html", "utf-8")
    # att["Content-Type"] = "application/octet-stream"
    # att["ContenT-Disposition"] = "attachment;filename = 'OpenAPI自动化测试报告.html '"
    #
    # msgRoot = MIMEMultipart('related')
    # msgRoot['Subject'] = subject
    # msgRoot['From'] = _format_addr(u'**测试组 <%s>' % sender)
    # msgRoot['To'] = _format_addr(u'OpenAPI项目组 <%s>' % receiver)
    # # msgRoot.attach(att)
    # msgRoot.attach(att)
    #
    # smtp = smtplib.SMTP()
    # smtp.connect(smtpserver)
    # smtp.login(user, password)
    # smtp.sendmail(sender, receiver, msgRoot.as_string())
    # smtp.quit()
    # print("邮件发布了")


    with open(file_new, 'rb') as fp:  # 读取文件内容
        msg = MIMEText(fp.read(), 'HTML', 'GB2312')  # 创建消息对象

    msg['Subject'] = "接口自动化报告"
    msg['From'] = formataddr(["陈驰", "chenchi@qtshe.com"])
    msg['To'] = formataddr(["陈驰", "chenchi@qtshe.com"])

    try:
        server = smtplib.SMTP()  # 创建一个 SMTP() 对象
        server.connect("smtp.qtshe.com", "80")  # 通过 connect 方法连接 smtp 主机
        # server.starttls() # 启动安全传输模式
        server.login("chenchi@qtshe.com", "cnp200@QTSHE")  # 邮箱账号登录校验
        server.sendmail("chenchi@qtshe.com", "chenchi@qtshe.com", msg.as_string())  # 邮件发送
        server.quit()  # 断开 smtp 连接
        print("邮件发送成功！")
    except Exception as e:
        print('失败：' + str(e))


# ======查找测试目录，找到最新生成的测试报告文件======
def new_report(test_report):
    lists = os.listdir(test_report)  # 列出目录的下所有文件和文件夹保存到lists
    # lists.sort(key=lambda fn: os.path.getmtime(test_report + "\\" + fn))  # 按时间排序 win
    lists.sort(key=lambda fn: os.path.getmtime(test_report + "/" + fn))  # linux
    file_new = os.path.join(test_report, lists[-1])  # 获取最新的文件保存到file_new
    print(file_new)
    return file_new

# if __name__ == "__main__":
#
#     send_file( r'C:\Users\Administrator\PycharmProjects\OpenAPI_new\Report\2017-10-26 20_08_07result.html')